package com.example.wanandroid_copy2.common.utils

import android.content.Context
import android.os.Environment
import java.io.File
import java.math.BigDecimal

object CacheManager {

    fun getCacheSize(context: Context): String {
        var cacheSize = getFolderSize(context.cacheDir)
        if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED) {
            cacheSize += getFolderSize(context.externalCacheDir)
        }
        return getFormatSize(cacheSize.toDouble())
    }

    fun clearCache(context: Context){
        deleteDir(context.cacheDir)
        if(Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED){
            deleteDir(context.externalCacheDir)
        }
    }

    private fun deleteDir(file: File?) : Boolean {
        file?.let {
            if(it.isDirectory){
                val list = it.list()
                list.forEachIndexed { index, _ ->
                    if(!deleteDir(File(it, list[index]))){
                        return false
                    }
                }
            }
            return it.delete()
        }
        return false
    }

    private fun getFolderSize(file: File?) : Long {
        file?.let {
            var size: Long = 0
            var files = file.listFiles()
            for (f in files) {
                if (f.isDirectory) {
                    size += getFolderSize(f)
                } else {
                    size += f.length()
                }
            }
            return size
        }
        return 0
    }

    private fun getFormatSize(size: Double): String {
        val kiloByte = size / 1024
        if (kiloByte < 1) {
            return size.toString() + "B"
        }

        val megaByte = kiloByte / 1024
        if (megaByte < 1) {
            val result1 = BigDecimal(java.lang.Double.toString(kiloByte))
            return result1.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "KB"
        }
        val gigaByte = megaByte / 1024
        if (gigaByte < 1) {
            val result2 = BigDecimal(java.lang.Double.toString(megaByte))
            return result2.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "MB"
        }
        val teraBytes = gigaByte / 1024
        if (teraBytes < 1) {
            val result3 = BigDecimal(java.lang.Double.toString(gigaByte))
            return result3.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "GB"
        }
        val result4 = BigDecimal(teraBytes)
        return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "TB"
    }
}